<?php

namespace app\user\controller;

use app\admin\service\ReportService;
use app\BaseController;
use app\model\ConfigModel;
use app\model\InterpretationRecordModel;
use app\model\MessageModel;
use app\model\ProxyEvaluationResultModel;
use app\model\SelfEvaluationResultModel;
use app\model\TaskModel;
use app\model\TaskUserModel;
use app\model\TaskUserResultModel;
use app\model\UserModel;
use app\model\not_del\UserModel as NotDelUserModel;

class Report extends BaseController
{
    /**
     * 验证家长密码
     * @return bool|string
     */
    public function validateParentPassword(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'password|家长密码' => 'require'
            ]);
            if (encrypt_password($param['password']) != $this->userData['parent_password'])
                throw new \Exception('密码错误！');
            return success([],'验证成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
    /**
     * 自我测评报告列表
     * @return bool|string
     */
    public function selfEvaluationList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['is_explain'])) {
                $where[] = ['is_explain', '=', $param['is_explain']];
            }
            if (!empty($param['answer_role'])) {
                $where[] = ['answer_role', '=', $param['answer_role']];
            }
            $where[] = ['uid', '=', $this->userData['id']];
            $where[] = ['user_del','=',0];
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            $query = $SelfEvaluationResultModel->where($where);
            $data = $query->with([
                'ratingScale' => function ($query) use ($param) {
                    $where = [];
                    if (!empty($param['name'])) {
                        $where[] = ['name', 'like', '%' . $param['name'] . '%'];
                    }
                    if (!empty($param['type_id'])) {
                        $where[] = ['type_id', '=', $param['type_id']];
                    }
                    $query->where($where);
                }
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评报告删除
     * @return bool|string
     */
    public function selfEvaluationDelete(): bool|string
    {
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_del'] != 1){
                throw new \Exception('用户不可主动删除报告！');
            }
            $id = $this->request->param('id');
            $SelfEvaluationResultModel = new SelfEvaluationResultModel();
            if (is_array($id)) {
                $SelfEvaluationResultModel->where([
                    ['id', 'in', $id],
                    ['uid', '=', $this->userData['id']]
                ])->update([
                    'user_del' => 1,
                ]);
            } else {
                $SelfEvaluationResultModel->where([
                    ['id', '=', $id],
                    ['uid', '=', $this->userData['id']]
                ])->update([
                    'user_del' => 1,
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评报告详情
     * @return bool|string
     */
    public function selfEvaluationInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSelfEvaluationReportInfo($id);
            $result_read_auth = explode(',',$data['info']['result_read_auth']);
            if (!in_array(3,$result_read_auth))
                throw new \Exception('您没有权限查看，请联系管理员！');
            $UserModel = new UserModel();
            $data['info']['explain_user_name'] = $UserModel->where('id','=',$data['info']['explain_uid'])->value('name');
            if ($data['info']['is_new'] == 1){
                $SelfEvaluationResultModel = new SelfEvaluationResultModel();
                $SelfEvaluationResultModel->where('id','=',$id)->update([
                    'is_new' => 0
                ]);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评报告详情-家长
     * @return bool|string
     */
    public function parentSelfEvaluationInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getSelfEvaluationReportInfo($id);
            $result_read_auth = explode(',',$data['info']['result_read_auth']);
            if (!in_array(4,$result_read_auth))
                throw new \Exception('您没有权限查看，请联系管理员！');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务测评报告列表
     * @return bool|string
     */
    public function TaskEvaluationList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $ResultWhere = [];
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $ResultWhere[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            } else {
                if (!empty($param['start_time'])) {
                    $ResultWhere[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $ResultWhere[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['answer_role'])) {
                $ResultWhere[] = ['answer_role', '=', $param['answer_role']];
            }
            $ResultWhere[] = ['uid', '=', $this->userData['id']];
            $ResultWhere[] = ['user_del', '=', 0];
            $TaskUserResultModel = new TaskUserResultModel();
            $taskList = $TaskUserResultModel->where($ResultWhere)->field('task_id,time')->select()->toArray();
            $taskData = [];
            foreach ($taskList as $v) {
                $taskData[$v['task_id']] = $v['time'];
            }
            $task_ids = array_column($taskList, 'task_id');
            $TaskUserModel = new TaskUserModel();
            $finishIds = $TaskUserModel->where([
                ['task_id', 'in', $task_ids],
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 0]
            ])->column('task_id');
            $finishIds = array_unique($finishIds);
            if (isset($param['is_finish']) && strlen($param['is_finish']) > 0) {
                if ($param['is_finish'] == 1) {
                    $task_ids = array_diff($task_ids, $finishIds);
                    if (!empty($task_ids)) {
                        $where[] = ['id', 'in', $task_ids];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                } else {
                    if (!empty($finishIds)) {
                        $where[] = ['id', 'in', $finishIds];
                    } else {
                        $where[] = ['id', '=', -1];
                    }
                }
            } else {
                $where[] = ['id', 'in', $task_ids];
            }
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['uid'])) {
                $where[] = ['uid', '=', $param['uid']];
            }
//            $NotDelUserModel = new NotDelUserModel();
            if (isset($param['role_mode']) && strlen($param['role_mode']) > 0) {
//                $uid = $NotDelUserModel->where([
//                    ['unit_id', '=', $this->userData['unit_id']],
//                    ['role_mode', '=', $param['role_mode']],
//                ])->column('id');
//                if (count($uid)){
//                    $where[] = ['uid', 'in', $uid];
//                }else{
//                    $where[] = ['id', '=', -1];
//                }
                $where[] = ['uid', '=', $param['role_mode']];
            }
            $TaskModel = new TaskModel();
            $query = $TaskModel->where($where);
            $data = $query->with([
                'userName'
            ])->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['time'] = $taskData[$item['id']]??0;
                if (in_array($item['id'], $finishIds)) {
                    $item['is_finish'] = 0;
                } else {
                    $item['is_finish'] = 1;
                }
            }
            $field = array_column($data['data'],'time');
            array_multisort($field, SORT_DESC, $data['data']);
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务详情
     * @return bool|string
     */
    public function taskInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $TaskModel = new TaskModel();
            $data = $TaskModel->where('id', '=', $id)->with([
                'userName'
            ])->find($id)->toArray();
            $TaskUserResultModel = new TaskUserResultModel();
            $data['time'] = $TaskUserResultModel->where([
                ['task_id', '=', $id],
                ['uid', '=', $this->userData['id']]
            ])->value('time');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告删除（删除整个任务的）
     * @return bool|string
     */
    public function TaskEvaluationDelete(): bool|string
    {
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_del'] != 1){
                throw new \Exception('用户不可主动删除报告！');
            }
            $id = $this->request->param('id');
            $TaskUserResultModel = new TaskUserResultModel();
            if (is_array($id)) {
                $TaskUserResultModel->where([
                    ['task_id', 'in', $id],
                    ['uid', '=', $this->userData['id']]
                ])->update([
                    'user_del' => 1
                ]);
            } else {
                $TaskUserResultModel->where([
                    ['task_id', '=', $id],
                    ['uid', '=', $this->userData['id']]
                ])->update([
                    'user_del' => 1
                ]);
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


    /**
     * 任务测评报告中间详情
     * @return bool|string
     */
    public function TaskEvaluationMiddleInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require|integer'
            ]);
            $where = [];
            $where[] = ['task_id', '=', $param['id']];
            if (!empty($param['uid'])){
                $where[] = ['uid', '=', $param['uid']];
            }else{
                $where[] = ['uid', '=', $this->userData['id']];
            }
            $TaskUserModel = new TaskUserModel();
            $data = $TaskUserModel->where($where)->with([
                'RatingScale' => function ($query) {
                    $query->with(['ratingScaleTypeName']);
                },
                'TaskUserResult'
            ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告右边详情
     * @return bool|string
     */
    public function TaskEvaluationRightInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTaskReportInfo($id);
            if (empty($data) || $data['user_del'] == 1) throw new \Exception('报告已被删除！');
            $result_read_auth = explode(',',$data['result_read_auth']);
            if (!in_array(3,$result_read_auth))
                throw new \Exception('您没有权限查看，请联系管理员！');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告右边详情-家长
     * @return bool|string
     */
    public function parentTaskEvaluationRightInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $ReportService = new ReportService($this->app);
            $data = $ReportService->getTaskReportInfo($id);
            if ($data['user_del'] == 1) throw new \Exception('报告已被删除！');
            $result_read_auth = explode(',',$data['result_read_auth']);
            if (!in_array(4,$result_read_auth))
                throw new \Exception('您没有权限查看，请联系管理员！');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除任务测评单个结果
     * @return bool|string
     */
    public function TaskEvaluationResultDelete(): bool|string
    {
        try {
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_del'] != 1){
                throw new \Exception('用户不可主动删除报告！');
            }
            $id = $this->request->param('id');
            $TaskUserResultModel = new TaskUserResultModel();
            $TaskUserResultModel->where('id', '=', $id)->update([
                'user_del' => 1,
            ]);
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 任务测评报告-申请解读
     * @return bool|string
     */
    public function TaskResultExplain(): bool|string
    {
        $TaskUserResultModel = new TaskUserResultModel();
        $TaskUserResultModel->startTrans();
        try {
            $id = $this->request->param('id');
            $info = $TaskUserResultModel->with(['RatingScaleName'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $InterpretationRecordModel = new InterpretationRecordModel();
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_explain'] == 1){
                //解读次数
                $explain_num = $InterpretationRecordModel->where([
                    ['uid','=',$this->userData['id']],
                    ['time','>',strtotime(date('Y-m-d'))]
                ])->count();
                if ($explain_num >= $config['explain_num']){
                    throw new \Exception('每日只能申请'.$config['explain_num'].'次');
                }
            }
            $InterpretationRecordModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'rating_scale_id' => $info['rating_scale_id'],
                'source' => 1,
                'result_id' => $id,
                'time' => time()
            ]);
            $info->save([
                'is_explain' => 2,
                'explain_apply_time' => time()
            ]);
            $TaskModel = new TaskModel();
            $uid = $TaskModel->where('id','=',$info['task_id'])->value('uid');
            $MessageModel = new MessageModel();
            $MessageModel->insert([
                'uid' => $uid,
                'type' => 9,
                'title' => '报告解读',
                'content' => $this->userData['name'].'用户向您申请了报告解读，解读量表：'.$info['rating_scale_name'].'量表，请及时处理。',
                'time' => time()
            ]);
            $TaskUserResultModel->commit();
            return success();
        } catch (\Exception $e) {
            $TaskUserResultModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 自我测评报告-申请解读
     * @return bool|string
     */
    public function SelfResultExplain(): bool|string
    {
        $SelfEvaluationResultModel = new SelfEvaluationResultModel();
        $SelfEvaluationResultModel->startTrans();
        try {
            $id = $this->request->param('id');
            $info = $SelfEvaluationResultModel->with(['RatingScaleName'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $InterpretationRecordModel = new InterpretationRecordModel();
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_explain'] == 1){
                //解读次数
                $explain_num = $InterpretationRecordModel->where([
                    ['uid','=',$this->userData['id']],
                    ['time','>',strtotime(date('Y-m-d'))]
                ])->count();
                if ($explain_num >= $config['explain_num']){
                    throw new \Exception('每日只能申请'.$config['explain_num'].'次');
                }
            }
            $InterpretationRecordModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'rating_scale_id' => $info['rating_scale_id'],
                'source' => 2,
                'result_id' => $id,
                'time' => time()
            ]);
            $info->save([
                'is_explain' => 2,
                'explain_apply_time' => time()
            ]);
            $UserModel = new UserModel();
            $uid = $UserModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['role_mode','=',1]
            ])->column('id');
            $MessageData = [];
            foreach ($uid as $v){
                $MessageData[] = [
                    'uid' => $v,
                    'type' => 9,
                    'title' => '报告解读',
                    'content' => $this->userData['name'].'用户向您申请了报告解读，解读量表：'.$info['rating_scale_name'].'量表，请及时处理。',
                    'time' => time()
                ];
            }
            if (count($MessageData)){
                $MessageModel = new MessageModel();
                $MessageModel->saveAll($MessageData,false);
            }
            $SelfEvaluationResultModel->commit();
            return success();
        } catch (\Exception $e) {
            $SelfEvaluationResultModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 他人代测报告-申请解读
     * @return bool|string
     */
    public function ProxyResultExplain(): bool|string
    {
        $ProxyEvaluationResultModel = new ProxyEvaluationResultModel();
        $ProxyEvaluationResultModel->startTrans();
        try {
            $id = $this->request->param('id');
            $info = $ProxyEvaluationResultModel->with(['RatingScaleName'])->find($id);
            if (!$info) throw new \Exception('参数错误！');
            $InterpretationRecordModel = new InterpretationRecordModel();
            $ConfigModel = new ConfigModel();
            $config = $ConfigModel->where([
                ['unit_id', '=', $this->userData['unit_id']],
                ['key','=','evaluation_report']
            ])->value('value');
            $config = json_decode($config,true);
            if ($config['is_explain'] == 1){
                //解读次数
                $explain_num = $InterpretationRecordModel->where([
                    ['uid','=',$this->userData['id']],
                    ['time','>',strtotime(date('Y-m-d'))]
                ])->count();
                if ($explain_num >= $config['explain_num']){
                    throw new \Exception('每日只能申请'.$config['explain_num'].'次');
                }
            }
            $InterpretationRecordModel->insert([
                'unit_id' => $this->userData['unit_id'],
                'uid' => $this->userData['id'],
                'rating_scale_id' => $info['rating_scale_id'],
                'source' => 3,
                'result_id' => $id,
                'time' => time()
            ]);
            $info->save([
                'is_explain' => 2,
                'explain_apply_time' => time()
            ]);
            $TaskModel = new TaskModel();
            $uid = $TaskModel->where('id','=',$info['task_id'])->value('uid');
            $MessageModel = new MessageModel();
            $MessageModel->insert([
                'uid' => $uid,
                'type' => 9,
                'title' => '报告解读',
                'content' => $this->userData['name'].'用户向您申请了报告解读，解读量表：'.$info['rating_scale_name'].'量表，请及时处理。',
                'time' => time()
            ]);
            $ProxyEvaluationResultModel->commit();
            return success();
        } catch (\Exception $e) {
            $ProxyEvaluationResultModel->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }
}